//
//  RequstMainTool.m
//  TestDemo
//
//  Created by zhangwenqiao on 2018/12/6.
//  Copyright © 2018年 zhangwenqiao. All rights reserved.
//

#import "RequstMainTool.h"
#import <AFNetworking.h>

@implementation RequstMainTool

/*
 外部调用 进行参数的传递 该层级进行参数的判断处理
 
 action: 必填 用来标识调用的是哪个接口 --重要--
 
 url:选填 可为空 后台只有一个网络地址：http://47.98.243.228:8081/app/v1
 dicBody:选填 可为空 后台接收参数为{header:{}, body:{}} Json类型    header在内层直接封装 只暴露body字典
 token:选填 可为空 某些接口需要进行token传递标识
 
 仿AF
 success:block参数 用来进行请求成功后的数据返回
 failure:block参数 用来进行请求失败后的错误返回
 */
+ (void)requestUrl:(NSString * _Nullable)url Action:(NSInteger)action BodyDic:(NSMutableDictionary * _Nullable)dicBody Token:(NSString * _Nullable)token success:(success)success failure:(failure)failure{
    NSURL *urlStr;
    if (url) {
        urlStr = [[NSURL alloc] initWithString:url];
    }else {
        urlStr = [[NSURL alloc]initWithString:@"http://47.98.243.228:8081/app/v1"];
    }
    if (action) {
        
    }else {
        NSLog(@"请求参数Action缺失");
        return;
    }
    
    if (dicBody == nil) {
        
    }else {
        
    }
    if (token) {
        
    }else {
        
    }
    [self requestRealizeUrl:urlStr Action:action BodyDic:dicBody Token:token success:success failure:failure];
}

/*
 参数为上层传递
 该方法进行数据请求的实现 在原生上嵌入AF的管理类 AF+原生
 因为后台进行的数据请求的参数传递为 x-www-form-urlencoded格式 不能使用AFNetworking  自己封装
 */
+ (void)requestRealizeUrl:(NSURL *)url Action:(NSInteger)action BodyDic:(NSMutableDictionary *)dicBody Token:(NSString *)token success:(success)success failure:(failure)failure{
    //参数处理
    NSDictionary *dic = [self parameterDicAction:action BodyDic:dicBody token:token];
    NSString *strParameters = [NSString stringWithFormat:@"request=%@", [self dictionryTransformString:dic.copy]];
    
    //请求头设置
    NSMutableData *postBody=[NSMutableData data];
    [postBody appendData:[strParameters dataUsingEncoding:NSUTF8StringEncoding]];
    NSMutableURLRequest *request=[[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10.0f];
    [request setHTTPMethod: @"POST"];
    [request setValue: @"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:postBody];
    //嵌入AF Request
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    AFJSONResponseSerializer* responseSerializer = [AFJSONResponseSerializer serializer];
    [responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"application/json",@"text/json",@"text/javascript",@"text/html",@"text/plain",nil]];
    manager.responseSerializer= responseSerializer;
    
    //仿照AF实现逻辑进行数据返回的封装
    __block NSURLSessionDataTask *dataTask = nil;
  
    NSURLSessionDataTask *task1 = [manager dataTaskWithRequest:request uploadProgress:^(NSProgress * _Nonnull uploadProgress) {
        
    } downloadProgress:^(NSProgress * _Nonnull downloadProgress) {
        
    } completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        if(error) {
            NSLog(@"Error: %@", error);
            if (failure) {
                failure(dataTask, error);
            }
        }else {
            NSLog(@"网络响应--%@", response);
            NSLog(@"请求得到数据--%@", responseObject);
            if (success) {
                success(dataTask, responseObject);
            }
        }
    }];
    [task1 resume];
}


/*
 纯原生请求封装  里面不接入第三方代码
 */
+ (void)protogenesis:(NSURL * _Nullable)url Action:(NSInteger)action BodyDic:(NSMutableDictionary * _Nullable)dicBody Token:(NSString * _Nullable)token success:(success)success failure:(failure)failure{
    //参数处理
    NSDictionary *dic = [self parameterDicAction:action BodyDic:dicBody token:token];
    NSString *strParameters = [NSString stringWithFormat:@"request=%@", [self dictionryTransformString:dic.copy]];
    
    //请求头设置
    NSMutableData *postBody=[NSMutableData data];
    [postBody appendData:[strParameters dataUsingEncoding:NSUTF8StringEncoding]];
    NSMutableURLRequest *request=[[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10.0f];
    [request setHTTPMethod: @"POST"];
    [request setValue: @"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:postBody];
    //仿照AF实现逻辑进行数据返回的封装
    __block NSURLSessionDataTask *dataTask = nil;
    
    //原生请求封装
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if(error) {
            NSLog(@"Error: %@", error);
            if (failure) {
                failure(dataTask, error);
            }
        }else {
            NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            NSLog(@"网络响应--%@", response);
            NSLog(@"请求得到数据--%@", result);
            if (success) {
                success(dataTask, result);
            }
        }
    }];
    [task resume];
    
    
    //15年方案  该类请求方法被废弃
    //    NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
    //    NSString *result = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
    //    NSLog(@"结果：%@",result);
}

#pragma mark--请求参数封装--
//直接将header在内层封装  外层只进行body传递
+ (NSDictionary *)parameterDicAction:(NSInteger)action BodyDic:(NSMutableDictionary *)bodyDic token:(NSString *)token{
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    
    NSMutableDictionary *dicHeader = [NSMutableDictionary dictionary];
    [dicHeader setValue:[NSString stringWithFormat:@"web"] forKey:@"plateForm"];
    [dicHeader setValue:[NSString stringWithFormat:@"1.0.0"] forKey:@"version"];
    if (token) {
        [dicHeader setValue:[NSString stringWithFormat:@"%@", token] forKey:@"token"];
    }else {
        [dicHeader setValue:[NSString stringWithFormat:@""] forKey:@"token"];
    }
    [dicHeader setValue:[NSString stringWithFormat:@"2018-09-20 13:12:11"] forKey:@"requestTime"];
    [dicHeader setValue:[NSString stringWithFormat:@"application/json"] forKey:@"contentType"];
    [dicHeader setValue:[NSString stringWithFormat:@"RSA"] forKey:@"encryp"];
    [dicHeader setValue:[NSString stringWithFormat:@"%ld", action] forKey:@"action"];
    
    NSMutableDictionary *dicBody = [NSMutableDictionary dictionary];
    if (bodyDic == nil) {
        
    }else {
        dicBody = bodyDic;
    }
    
    [dic setValue:dicHeader forKey:@"header"];
    [dic setValue:dicBody forKey:@"body"];
    
    NSDictionary *dicc = [NSDictionary dictionaryWithDictionary:dic];
    return dicc;
}

#pragma mark-字典转字符串-
//后台定义必须为 request=%@ 格式 将字典Json转换成字符串
+ (NSString *)dictionryTransformString:(NSMutableDictionary *)dic {
    NSError *error;
    NSLog(@"dic--%@", dic);
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic
                                                       options:NSJSONWritingPrettyPrinted
                                                         error:&error];
    NSLog(@"jsonData--%@", jsonData);
    NSString *str = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    NSLog(@"str--%@", str);
    return str;
}

@end
